package com.cloud.rocketmqtxprovider.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.cloud.rocketmqtxprovider.component.SendMessage;
import com.cloud.rocketmqtxprovider.entity.Order;
import com.cloud.rocketmqtxprovider.entity.TransactionInformation;
import com.cloud.rocketmqtxprovider.mapper.OrderMapper;
import com.cloud.rocketmqtxprovider.mapper.TransactionInformationMapper;
import com.cloud.rocketmqtxprovider.service.ProviderService;
import org.apache.rocketmq.client.exception.MQClientException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@SuppressWarnings("all")
public class ProviderServiceImpl implements ProviderService {

    private static final String MESSAGE_TOPIC="transaction_topic_order";

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TransactionInformationMapper transactionInformationMapper;

    @Autowired
    private SendMessage sendMessage;

    @Override
    @Transactional
    public int insertOrder(Order order,String transactionId) {

        //正常的业务逻辑
        orderMapper.insert(order);

        //添加执行结果到事务记录表，表明事务已经执行完了
        TransactionInformation information = TransactionInformation.builder().transactionId(transactionId).build();
        transactionInformationMapper.insertSelective(information);
        return 1;
    }

    @Override
    public int selectTransactionCount(String transactionId) {
        return transactionInformationMapper.selectTransactionInformationCountById(transactionId);
    }

    @Override
    public String insertOrder(Order order)throws MQClientException {
        String data = JSONObject.toJSONString(order);
        sendMessage.sendMessage(data, MESSAGE_TOPIC);
        return "执行成功";
    }
}
